package com.syaccp.config.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.syaccp.config.security.handler.AuthenticationEntryPointImpl;
import com.syaccp.config.security.handler.CustomerAuthenticationException;
import com.syaccp.model.SysUser;
import com.syaccp.utils.JwtUtil;
import com.syaccp.utils.RedisCache;

import io.jsonwebtoken.Claims;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
	private AuthenticationEntryPointImpl authenticationEntryPoint ;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        try {
			//解析token
			String userid;
			try {
			    Claims claims = JwtUtil.parseJWT(token);
			    userid = claims.getSubject();
			} catch (Exception e) {
			    e.printStackTrace();
			    throw new CustomerAuthenticationException("token非法");
			}
			//从redis中获取用户信息
			String redisKey = "login:" + userid;
			SysUser loginUser = redisCache.getCacheObject(redisKey);
			if(Objects.isNull(loginUser)){
			    throw new CustomerAuthenticationException("用户未登录");
			}
			//存入SecurityContextHolder
			//TODO 获取权限信息封装到Authentication中
			UsernamePasswordAuthenticationToken authenticationToken =
			        new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
			SecurityContextHolder.getContext().setAuthentication(authenticationToken);
			//放行
			filterChain.doFilter(request, response);
		} catch (AuthenticationException e) {
			try {
				authenticationEntryPoint.commence(request, response, e);
			} catch (IOException e1) {
				throw e1;
			} catch (ServletException e2) {
				throw e2;
			}
		} 
    }
}
